package com.aiyige.page.my.download;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.db.DBHelper;
import com.aiyige.base.db.dao.DownloadFileDao;
import com.aiyige.base.db.dao.DownloadModelDao;
import com.aiyige.base.db.table.DownloadFile;
import com.aiyige.base.db.table.DownloadModel;
import com.aiyige.page.my.download.adapter.DownloadFileAdapter;
import com.aiyige.page.my.download.util.DownloadUtil;
import com.aiyige.page.player.PlayerInfo;
import com.aiyige.utils.ToastX;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.j256.ormlite.misc.TransactionManager;
import com.j256.ormlite.stmt.UpdateBuilder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import timber.log.Timber;

@Route(path = ARouterConfig.DownloadDetailPage)
public class DownloadDetailPage extends AppCompatActivity {

    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.titleActionBtn)
    Button titleActionBtn;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.editLayout)
    ViewGroup editLayout;
    @BindView(R.id.selectAllIv)
    ImageView selectAllIv;

    boolean edit;
    DownloadFileAdapter downloadFileAdapter;
    @Autowired
    int parentType;
    @Autowired
    String parentId;
    @Autowired
    String title;
    BroadcastReceiver broadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_download_detail);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        titleActionBtn.setText(R.string.edit);
        titleTv.setText(title);
        edit = false;
        updateTitleActionBtn();
        updateEditLayout();
        downloadFileAdapter = new DownloadFileAdapter();
        downloadFileAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                DownloadFile downloadFile = downloadFileAdapter.getItem(position);
                if (!edit) {
                    if (downloadFile.getProgressStatus() != DownloadUtil.PROGRESS_STATUS_DOWNLOAD_FINISHED)
                        return;
                    List<PlayerInfo> playList = new ArrayList<>();
                    playList.add(PlayerInfo.newBuilder()
                            .cover(TextUtils.isEmpty(downloadFile.getCoverLocalUrl()) ? downloadFile.getCoverRemoteUrl() : downloadFile.getCoverLocalUrl())
                            .isFree(true)
                            .path(downloadFile.getFileLocalUrl())
                            .title(downloadFile.getTitle())
                            .build());
                    ARouter.getInstance()
                            .build(ARouterConfig.PlayerPage)
                            .withSerializable("playList", (Serializable) playList)
                            .withString("modelId", parentId)
                            .withInt("fileId", downloadFile.getId())
                            .navigation();
                } else {
                    downloadFile.setSelected(!downloadFile.isSelected());
                    downloadFileAdapter.setData(position, downloadFile);
                    updateSelectAllIv();
                }
            }
        });
        downloadFileAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                DownloadFile downloadFile = downloadFileAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.statusLayout: {
                        switch (downloadFile.getControlOption()) {
                            case DownloadUtil.CONTROL_OPTION_DOWNLOAD:
                                try {
                                    UpdateBuilder<DownloadFile, Integer> updateBuilder = DownloadFileDao.getDao().updateBuilder();
                                    updateBuilder.updateColumnValue(DownloadFile.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_PAUSE);
                                    updateBuilder.where().eq(DownloadFile.ID_FIELD, downloadFile.getId());
                                    updateBuilder.update();
                                    downloadFile.setControlOption(DownloadUtil.CONTROL_OPTION_PAUSE);
                                    downloadFileAdapter.setData(position, downloadFile);
                                } catch (Exception e) {
                                    ToastX.show(e.getMessage());
                                }
                                break;
                            case DownloadUtil.CONTROL_OPTION_PAUSE:
                                try {
                                    UpdateBuilder<DownloadFile, Integer> updateBuilder = DownloadFileDao.getDao().updateBuilder();
                                    updateBuilder.updateColumnValue(DownloadFile.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DOWNLOAD);
                                    updateBuilder.updateColumnValue(DownloadFile.DOWNLOAD_TIMESTAMP_FIELD, 0);
                                    updateBuilder.where().eq(DownloadFile.ID_FIELD, downloadFile.getId());
                                    updateBuilder.update();
                                    downloadFile.setControlOption(DownloadUtil.CONTROL_OPTION_DOWNLOAD);
                                    downloadFileAdapter.setData(position, downloadFile);
                                    DownloadUtil.startDownload();
                                } catch (Exception e) {
                                    ToastX.show(e.getMessage());
                                }
                                break;
                        }
                        break;
                    }
//                    case R.id.selectLayout: {
//                        downloadFile.setSelected(!downloadFile.isSelected());
//                        downloadFileAdapter.setData(position, downloadFile);
//                        updateSelectAllIv();
//                        break;
//                    }
                }
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setItemAnimator(null);
        downloadFileAdapter.bindToRecyclerView(recyclerView);
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    String action = intent.getAction();
                    switch (action) {
                        case DownloadUtil.ACTION_DOWNLOAD_UPDATE:
                            query();
                            break;
                    }
                } catch (Exception e) {

                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(DownloadUtil.ACTION_DOWNLOAD_UPDATE);
        registerReceiver(broadcastReceiver, intentFilter);
        DownloadUtil.startDownload();
    }

    @Override
    protected void onResume() {
        super.onResume();
        query();
    }

    @Override
    protected void onDestroy() {
        try {
            unregisterReceiver(broadcastReceiver);
        } catch (Exception e) {

        }
        super.onDestroy();
    }

    public void query() {
        DownloadUtil.scanDownload();
        List<DownloadFile> downloadFileList = new LinkedList<>();
        try {
            downloadFileList.addAll(
                    DownloadFileDao.getDao().queryBuilder()
                            .where()
                            .eq(DownloadFile.PARENT_ID_FIELD, parentId)
                            .and()
                            .ne(DownloadFile.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE)
                            .and()
                            .ne(DownloadFile.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE_RECORD_ONLY)
                            .query());
        } catch (Exception e) {

        }

        for (DownloadFile downloadFile : downloadFileList) {
            downloadFile.setEdit(edit);
        }
        if (edit) {
            List<DownloadFile> oldList = downloadFileAdapter.getData();
            outerLoop:
            for (DownloadFile oldFile : oldList) {
                for (DownloadFile newFile : downloadFileList) {
                    if (oldFile.getId() == newFile.getId()) {
                        newFile.setSelected(oldFile.isSelected());
                        continue outerLoop;
                    }
                }
            }
        }
        downloadFileAdapter.setNewData(downloadFileList);
    }

    public void updateEditLayout() {
        if (edit) {
            editLayout.setVisibility(View.VISIBLE);
        } else {
            editLayout.setVisibility(View.GONE);
        }
    }

    public void updateTitleActionBtn() {
        titleActionBtn.setText(edit ? R.string.cancel : R.string.edit);
    }

    @OnClick({R.id.titleBackBtn, R.id.titleActionBtn, R.id.selectAllBtn, R.id.deleteBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.titleActionBtn:
                edit = !edit;
                updateEditLayout();
                updateTitleActionBtn();
                updateEditState();
                updateSelectAllIv();
                break;
            case R.id.selectAllBtn:
                if (!checkAllSelected()) {
                    doSelectAll();
                } else {
                    unSelectAll();
                }
                updateSelectAllIv();
                break;
            case R.id.deleteBtn:
                try {
                    TransactionManager.callInTransaction(DBHelper.getInstance().getConnectionSource(), new Callable<Object>() {
                        @Override
                        public Object call() throws Exception {
                            boolean deleteAll = true;
                            int unselectedNum = 0;
                            for (DownloadFile downloadFile : downloadFileAdapter.getData()) {
                                if (downloadFile.isSelected()) {
                                    UpdateBuilder<DownloadFile, Integer> updateBuilder = DownloadFileDao.getDao().updateBuilder();
                                    updateBuilder.updateColumnValue(DownloadFile.CONTROL_OPTION_FIELD, parentType != DownloadUtil.MODEL_TYPE_LOCAL_VIDEO ? DownloadUtil.CONTROL_OPTION_DELETE : DownloadUtil.CONTROL_OPTION_DELETE_RECORD_ONLY);
                                    updateBuilder.where().eq(DownloadFile.ID_FIELD, downloadFile.getId());
                                    updateBuilder.update();
                                } else {
                                    deleteAll = false;
                                    unselectedNum++;
                                }
                            }
                            if (deleteAll) {
                                UpdateBuilder<DownloadModel, String> updateBuilder = DownloadModelDao.getDao().updateBuilder();
                                updateBuilder.updateColumnValue(DownloadModel.CONTROL_OPTION_FIELD, parentType != DownloadUtil.MODEL_TYPE_LOCAL_VIDEO ? DownloadUtil.CONTROL_OPTION_DELETE : DownloadUtil.CONTROL_OPTION_DELETE_RECORD_ONLY);
                                updateBuilder.where().eq(DownloadModel.ID_FIELD, parentId);
                                updateBuilder.update();
                                DownloadUtil.sendDownloadProgressStatusUpdateBroadcast();
                                finish();
                            } else {
                                UpdateBuilder<DownloadModel, String> updateBuilder = DownloadModelDao.getDao().updateBuilder();
                                updateBuilder.updateColumnValue(DownloadModel.MEDIA_NUM, unselectedNum);
                                updateBuilder.where().eq(DownloadModel.ID_FIELD, parentId);
                                updateBuilder.update();
                                DownloadUtil.sendDownloadProgressStatusUpdateBroadcast();
                                query();
                            }
                            return null;
                        }
                    });
                } catch (Exception e) {
                    Timber.e("onViewClicked:" + Log.getStackTraceString(e));
                }
                break;
        }
    }

    public void doSelectAll() {
        for (DownloadFile downloadFile : downloadFileAdapter.getData()) {
            downloadFile.setSelected(true);
        }
        downloadFileAdapter.notifyDataSetChanged();
    }

    public void unSelectAll() {
        for (DownloadFile downloadFile : downloadFileAdapter.getData()) {
            downloadFile.setSelected(false);
        }
        downloadFileAdapter.notifyDataSetChanged();
    }


    public void updateEditState() {
        for (DownloadFile downloadFile : downloadFileAdapter.getData()) {
            downloadFile.setEdit(edit);
        }
        downloadFileAdapter.notifyDataSetChanged();
    }

    public boolean checkAllSelected() {
        boolean result = true;
        for (DownloadFile downloadFile : downloadFileAdapter.getData()) {
            if (!downloadFile.isSelected()) {
                result = false;
                break;
            }
        }
        return result;
    }


    public void updateSelectAllIv() {
        if (checkAllSelected()) {
            selectAllIv.setImageResource(R.drawable.order_screen_selected);
        } else {
            selectAllIv.setImageResource(R.drawable.order_screen_normal);
        }
    }

}
